<template>
  <div class="approval-history">
    <a-spin :loading="loading">
      <!-- 审批统计 -->
      <div class="approval-stats">
        <a-row :gutter="16">
          <a-col :span="6">
            <a-statistic
              title="总审批次数"
              :value="stats.totalApprovals"
              :value-style="{ color: '#165dff' }"
            />
          </a-col>
          <a-col :span="6">
            <a-statistic
              title="通过次数"
              :value="stats.approvedCount"
              :value-style="{ color: '#00b42a' }"
            />
          </a-col>
          <a-col :span="6">
            <a-statistic
              title="驳回次数"
              :value="stats.rejectedCount"
              :value-style="{ color: '#f53f3f' }"
            />
          </a-col>
          <a-col :span="6">
            <a-statistic
              title="平均处理时长"
              :value="stats.avgProcessTime"
              suffix="小时"
              :value-style="{ color: '#ff7d00' }"
            />
          </a-col>
        </a-row>
      </div>

      <a-divider />

      <!-- 审批时间线 -->
      <div class="approval-timeline">
        <h3 class="section-title">审批历史</h3>
        
        <a-timeline>
          <a-timeline-item 
            v-for="(record, index) in approvalRecords" 
            :key="record.approvalId"
            :dot-color="getTimelineDotColor(record.approvalResult)"
          >
            <template #dot>
              <IconCheckCircle v-if="record.approvalResult === 'APPROVED'" class="timeline-icon success" />
              <IconCloseCircle v-else-if="record.approvalResult === 'REJECTED'" class="timeline-icon error" />
            </template>
            
            <div class="timeline-content">
              <div class="timeline-header">
                <div class="timeline-title">
                  <span class="approval-stage">{{ getApprovalStageText(record.approvalStage) }}</span>
                  <a-tag :color="getApprovalResultColor(record.approvalResult)" size="small">
                    {{ getApprovalResultText(record.approvalResult) }}
                  </a-tag>
                </div>
                <div class="timeline-time">{{ record.approvalTime }}</div>
              </div>
              
              <div class="timeline-body">
                <div class="approval-info">
                  <div class="info-row">
                    <span class="info-label">审批人：</span>
                    <span class="info-value">{{ record.approver }}</span>
                  </div>
                  <div class="info-row">
                    <span class="info-label">审批部门：</span>
                    <span class="info-value">{{ record.approverDepartment }}</span>
                  </div>
                  <div class="info-row" v-if="record.processTime">
                    <span class="info-label">处理时长：</span>
                    <span class="info-value">{{ record.processTime }}</span>
                  </div>
                </div>
                
                <div class="approval-comment" v-if="record.approvalComment">
                  <div class="comment-label">审批意见：</div>
                  <div class="comment-content">{{ record.approvalComment }}</div>
                </div>
                
                <!-- 附件 -->
                <div class="approval-attachments" v-if="record.attachments && record.attachments.length > 0">
                  <div class="attachments-label">相关附件：</div>
                  <div class="attachments-list">
                    <a-space wrap>
                      <a-tag 
                        v-for="attachment in record.attachments" 
                        :key="attachment.fileId"
                        color="blue"
                        class="attachment-tag"
                        @click="downloadAttachment(attachment)"
                      >
                        <IconFile />{{ attachment.fileName }}
                      </a-tag>
                    </a-space>
                  </div>
                </div>
              </div>
            </div>
          </a-timeline-item>
          
          <!-- 提交申请节点 -->
          <a-timeline-item dot-color="blue">
            <template #dot>
              <IconSend class="timeline-icon submit" />
            </template>
            
            <div class="timeline-content">
              <div class="timeline-header">
                <div class="timeline-title">
                  <span class="approval-stage">提交申请</span>
                  <a-tag color="blue" size="small">已提交</a-tag>
                </div>
                <div class="timeline-time">{{ submitTime }}</div>
              </div>
              
              <div class="timeline-body">
                <div class="approval-info">
                  <div class="info-row">
                    <span class="info-label">申请人：</span>
                    <span class="info-value">{{ submitter }}</span>
                  </div>
                  <div class="info-row">
                    <span class="info-label">申请企业：</span>
                    <span class="info-value">{{ enterpriseName }}</span>
                  </div>
                </div>
                
                <div class="approval-comment">
                  <div class="comment-label">申请说明：</div>
                  <div class="comment-content">{{ submitComment }}</div>
                </div>
              </div>
            </div>
          </a-timeline-item>
        </a-timeline>
      </div>
    </a-spin>
  </div>
</template>

<script setup>
import { onMounted, ref } from 'vue';
import { Message } from '@arco-design/web-vue';
import {
  IconCheckCircle,
  IconCloseCircle,
  IconSend,
  IconFile
} from '@arco-design/web-vue/es/icon';

// 定义props
const props = defineProps({
  subsidyApplicationId: {
    type: String,
    required: true
  }
});

// 响应式数据
const loading = ref(false);
const approvalRecords = ref([]);
const stats = ref({
  totalApprovals: 0,
  approvedCount: 0,
  rejectedCount: 0,
  avgProcessTime: 0
});
const submitTime = ref('2024-01-08 09:00:00');
const submitter = ref('张三');
const enterpriseName = ref('晋江绿化有限公司');
const submitComment = ref('申请森林生态修复项目补贴，项目总面积120.5亩，已完成验收工作，申请补贴资金15万元。');

// 模拟审批记录数据
const mockApprovalRecords = [
  {
    approvalId: 'APPROVAL003',
    approvalStage: 'FINAL_REVIEW',
    approvalResult: 'PENDING',
    approver: '林业局-王局长',
    approverDepartment: '晋江市林业局',
    approvalTime: '2024-01-22 14:30:00',
    approvalComment: '正在进行最终审核，预计3个工作日内完成。',
    processTime: null,
    attachments: []
  },
  {
    approvalId: 'APPROVAL002',
    approvalStage: 'TECHNICAL_REVIEW',
    approvalResult: 'APPROVED',
    approver: '林业局-李工程师',
    approverDepartment: '晋江市林业局技术科',
    approvalTime: '2024-01-18 16:45:00',
    approvalComment: '经技术审核，该项目符合森林生态修复标准，验收材料齐全，同意通过技术审核。建议进入最终审批流程。',
    processTime: '2天8小时',
    attachments: [
      {
        fileId: 'ATT001',
        fileName: '技术审核报告.pdf'
      },
      {
        fileId: 'ATT002',
        fileName: '现场勘查照片.zip'
      }
    ]
  },
  {
    approvalId: 'APPROVAL001',
    approvalStage: 'INITIAL_REVIEW',
    approvalResult: 'APPROVED',
    approver: '林业局-陈科长',
    approverDepartment: '晋江市林业局审批科',
    approvalTime: '2024-01-15 10:20:00',
    approvalComment: '初步审核通过，申请材料完整，项目符合补贴政策要求。转入技术审核环节。',
    processTime: '5天2小时',
    attachments: [
      {
        fileId: 'ATT003',
        fileName: '初审意见书.pdf'
      }
    ]
  }
];

// 获取审批阶段文本
const getApprovalStageText = (stage) => {
  const textMap = {
    'INITIAL_REVIEW': '初步审核',
    'TECHNICAL_REVIEW': '技术审核',
    'FINAL_REVIEW': '最终审批',
    'PAYMENT_APPROVAL': '支付审批',
    'COMPLETION_REVIEW': '完工审核'
  };
  return textMap[stage] || '未知阶段';
};

// 获取审批结果文本
const getApprovalResultText = (result) => {
  const textMap = {
    'PENDING': '待审批',
    'APPROVED': '通过',
    'REJECTED': '驳回',
    'RETURNED': '退回'
  };
  return textMap[result] || '未知';
};

// 获取审批结果颜色
const getApprovalResultColor = (result) => {
  const colorMap = {
    'PENDING': 'orange',
    'APPROVED': 'green',
    'REJECTED': 'red',
    'RETURNED': 'blue'
  };
  return colorMap[result] || 'gray';
};

// 获取时间线点颜色
const getTimelineDotColor = (result) => {
  const colorMap = {
    'PENDING': '#ff7d00',
    'APPROVED': '#00b42a',
    'REJECTED': '#f53f3f',
    'RETURNED': '#165dff'
  };
  return colorMap[result] || '#86909c';
};

// 下载附件
const downloadAttachment = (attachment) => {
  console.log('下载附件:', attachment);
  Message.success(`开始下载: ${attachment.fileName}`);
};

// 计算统计数据
const calculateStats = (records) => {
  const total = records.length;
  const approved = records.filter(r => r.approvalResult === 'APPROVED').length;
  const rejected = records.filter(r => r.approvalResult === 'REJECTED').length;
  
  // 计算平均处理时长（简化计算）
  const processedRecords = records.filter(r => r.processTime);
  const avgTime = processedRecords.length > 0 ? 
    Math.round(processedRecords.reduce((sum, r) => {
      // 简化处理时长解析
      const match = r.processTime.match(/(\d+)天/);
      return sum + (match ? parseInt(match[1]) * 24 : 24);
    }, 0) / processedRecords.length) : 0;
  
  return {
    totalApprovals: total,
    approvedCount: approved,
    rejectedCount: rejected,
    avgProcessTime: avgTime
  };
};

// 加载审批历史
const loadApprovalHistory = () => {
  loading.value = true;
  
  setTimeout(() => {
    approvalRecords.value = mockApprovalRecords;
    stats.value = calculateStats(mockApprovalRecords);
    loading.value = false;
  }, 300);
};

// 组件挂载时加载数据
onMounted(() => {
  loadApprovalHistory();
});
</script>

<style scoped>
.approval-history {
  padding: 16px;
}

.approval-stats {
  background: #f7f8fa;
  padding: 20px;
  border-radius: 6px;
  margin-bottom: 16px;
}

.section-title {
  margin: 0 0 20px 0;
  font-size: 16px;
  font-weight: 600;
  color: #1d2129;
}

.timeline-content {
  padding-bottom: 20px;
}

.timeline-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 12px;
}

.timeline-title {
  display: flex;
  align-items: center;
  gap: 8px;
}

.approval-stage {
  font-size: 16px;
  font-weight: 600;
  color: #1d2129;
}

.timeline-time {
  font-size: 14px;
  color: #86909c;
}

.timeline-body {
  background: #f7f8fa;
  padding: 16px;
  border-radius: 6px;
  border-left: 3px solid #165dff;
}

.approval-info {
  margin-bottom: 12px;
}

.info-row {
  display: flex;
  margin-bottom: 6px;
}

.info-label {
  min-width: 80px;
  color: #86909c;
  font-size: 14px;
}

.info-value {
  color: #1d2129;
  font-size: 14px;
}

.approval-comment {
  margin-bottom: 12px;
}

.comment-label {
  color: #86909c;
  font-size: 14px;
  margin-bottom: 6px;
}

.comment-content {
  color: #1d2129;
  font-size: 14px;
  line-height: 1.6;
  background: white;
  padding: 12px;
  border-radius: 4px;
  border: 1px solid #e5e6eb;
}

.approval-attachments {
  margin-top: 12px;
}

.attachments-label {
  color: #86909c;
  font-size: 14px;
  margin-bottom: 8px;
}

.attachment-tag {
  cursor: pointer;
  transition: all 0.3s;
}

.attachment-tag:hover {
  transform: translateY(-1px);
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}

.timeline-icon {
  font-size: 16px;
}

.timeline-icon.success {
  color: #00b42a;
}

.timeline-icon.error {
  color: #f53f3f;
}

.timeline-icon.pending {
  color: #ff7d00;
}

.timeline-icon.submit {
  color: #165dff;
}

:deep(.arco-timeline-item-content) {
  min-height: auto;
}

:deep(.arco-timeline-item-dot) {
  width: 12px;
  height: 12px;
  border-width: 2px;
}

:deep(.arco-statistic-title) {
  font-size: 14px;
  color: #86909c;
}

:deep(.arco-statistic-content) {
  font-size: 20px;
  font-weight: 600;
}
</style>